package com.deep.deepenterpise.common.util;

import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.SecureRandom;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

@Component
public class DrCommonUtil {

    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static final Random RANDOM = new SecureRandom();

    /**
     * @Auth Jiang Zhan
     * @Desc 获取时间戳
     * @Time 2020年09月24日15:59:43
     */
    public String getTimeStamp()
    {
        return String.valueOf(System.currentTimeMillis()/1000);
    }

    /**
     * @Auth Jiang Zhan
     * @Desc 获取时间戳
     * @Time 2020年09月24日15:59:43
     */
    public static String drGetTimeStamp()
    {
        return String.valueOf(System.currentTimeMillis()/1000);
    }

    /**
     * @Auth Jiang Zhan
     * @Desc 获取UUID
     * @Time 2020年09月24日15:59:43
     */
    public String getUUID(){
        String uuid="";
        for(int i=0;i<10;i++){
           uuid = UUID.randomUUID().toString().replaceAll("-", "");
        }
        return uuid;
    }

    /**
     * @Auth Jiang Zhan
     * @Desc 获取指定时间戳的时间
     * @Time 2020年09月24日15:59:43
     */
    public String drGetTimeStampToTime(Long drTimeStamp)
    {
        Instant drInstant = Instant.ofEpochSecond(drTimeStamp);
        LocalDateTime dateTime = LocalDateTime.ofInstant(drInstant, ZoneId.systemDefault());

        // 定义时间格式
        DateTimeFormatter drFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 格式化时间
        return dateTime.format(drFormatter);
    }

    /**
     * @Auth Jiang Zhan
     * @Desc 获取指定时间戳
     * @Time 2020年09月24日15:59:43
     */
    public String drGetSpecifyTimeStamp(String drTime)
    {
        long drSpecifyTimeStamp = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).parse(drTime, new ParsePosition(0)).getTime() / 1000;
        return String.valueOf(drSpecifyTimeStamp);
    }

    /**
     * @Auth Jiang Zhan
     * @Desc 计算两个时间戳之间的时间
     * @Time 2020年09月24日15:59:43
     */
    public static long drCalculateDaysBetweenTimestamps(String drStartTime, String drEndTime)
    {

        DateTimeFormatter drFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate drStartTimeTmp = LocalDate.parse(drStartTime, drFormatter);
        LocalDate drEndTimeTmp = LocalDate.parse(drEndTime, drFormatter);

        long drDaysBetween = ChronoUnit.DAYS.between(drStartTimeTmp, drEndTimeTmp);

        return Math.abs(drDaysBetween);
    }

    /**
     * @Auth Jiang Zhan
     * @Desc 获取当日时间戳
     * @Time 2020年09月24日15:59:43
     */
    public Map<String, String> drGetTodayTimeStamp() {
        Map<String, String> dr_time = new HashMap<>();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
            sdf.applyPattern("yyyy-MM-dd");// a为am/pm的标记
            Date date = new Date();// 获取当前时间
            String maxDateStr = sdf.format(date);
            String minDateStr = "";
            Calendar calc = Calendar.getInstance();
            calc.setTime(sdf.parse(maxDateStr));
            calc.add(calc.DATE, 0);
            Date minDate = calc.getTime();
            minDateStr = sdf.format(minDate);
            dr_time.put("drStartTime", drGetSpecifyTimeStamp(minDateStr + " 00:00:00"));
            dr_time.put("drEndTime", drGetSpecifyTimeStamp(minDateStr + " 23:59:59"));
            return dr_time;
        }catch (Exception e){
            return dr_time;
        }
    }

    /**
     * @Auth Jiang Zhan
     * @Desc 获取当日时间戳
     * @Time 2020年09月24日15:59:43
     */
    public static String drGetOrderIdByTime() {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate=sdf.format(new Date());
        String result="";
        Random random=new Random();
        for(int i=0;i<3;i++){
            result+=random.nextInt(10);
        }
        return newDate+result;
    }

    /**
     * @Auth Jiang Zhan
     * @Desc 获取随机的32个字符
     * @Time 2020年09月24日15:59:43
     */
    public static String drGenerateNonceStr() {
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }

    /**
     * @Auth Jiang Zhan
     * @Desc url拼接处理
     * @Time 2020年09月24日15:59:43
     */
    public static String drUrlEncode(final Map<String, String> drData, String drKey)
    {
        Set<String> drKeySet = drData.keySet();
        String[] drKeyArray = drKeySet.toArray(new String[drKeySet.size()]);
        Arrays.sort(drKeyArray);
        StringBuilder drUrlEncode = new StringBuilder();
        for (String drKeyTmp : drKeyArray)
        {
            if (drData.get(drKeyTmp).trim().length() > 0)
                drUrlEncode.append(drKeyTmp).append("=").append(drData.get(drKeyTmp).trim()).append("&");
        }
        drUrlEncode.append("key=").append(drKey);
        return drUrlEncode.toString();
    }

    public Map<String,String> drGetDistanceTime(String drStart, String drEnd) {
        Map<String,String> drGetDistanceTime = new HashMap<>();
        long drDay = 0;
        long drHour = 0;
        long drMin = 0;
        long drSec = 0;
        long drStartTime = Long.parseLong(drStart) * 1000;
        long drEndTime = Long.parseLong(drEnd) * 1000;
        long drDiff ;
        drDiff = drEndTime - drStartTime;
        drDay = drDiff / (24 * 60 * 60 * 1000);
        drHour = (drDiff / (60 * 60 * 1000) - drDay * 24);
        drMin = ((drDiff / (60 * 1000)) - drDay * 24 * 60 - drHour * 60);
        drSec = ((drDiff/1000) -drDay * 24 * 60* 60 - drHour * 60* 60 - drMin* 60);
        if(drHour == 0){
            drGetDistanceTime.put("drMin",String.valueOf(drMin));
            drGetDistanceTime.put("drSec",String.valueOf(drSec));
        }
        if(drDay == 0){
            drGetDistanceTime.put("drHour",String.valueOf(drHour));
            drGetDistanceTime.put("drMin",String.valueOf(drMin));
            drGetDistanceTime.put("drSec",String.valueOf(drSec));
        }
        if(drDay>0){
            drGetDistanceTime.put("drDay",String.valueOf(drDay));
            drGetDistanceTime.put("drHour",String.valueOf(drHour));
            drGetDistanceTime.put("drMin",String.valueOf(drMin));
            drGetDistanceTime.put("drSec",String.valueOf(drSec));
        }
        return drGetDistanceTime;
    }

    /**
     * @Auth Jiang Zhan
     * @Desc 获取e.printStackTrace() 的具体信息
     * @Time 2020年09月24日15:59:43
     */
    public static String drGetStackTraceInfo(Exception drException) {

        StringWriter drSInfo = null;
        PrintWriter drPInfo = null;

        try {
            drSInfo = new StringWriter();
            drPInfo = new PrintWriter(drSInfo);
            drException.printStackTrace(drPInfo);//将出错的栈信息输出到printWriter中
            drPInfo.flush();
            drSInfo.flush();

            return drSInfo.toString();
        } catch (Exception ex) {
            return "发生错误";
        } finally {
            if (drSInfo != null) {
                try {
                    drSInfo.close();
                } catch (IOException drIOException) {
                    drIOException.printStackTrace();
                }
            }
            if (drPInfo != null) {
                drPInfo.close();
            }
        }
    }

    public static String convertHexToString(String hex) {
        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();
        for (int i = 0; i < hex.length() - 1; i += 2) {
            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            //convert hex to decimal
            int decimal = Integer.parseInt(output.trim(), 16);
            //convert the decimal to character
            sb.append((char) decimal);
            temp.append(decimal);
        }
        return sb.toString();
    }

    /**
     * @Auth Jiang Zhan
     * @Desc 获取时间表名
     * @Time 2020年09月24日15:59:43
     */
    public static String drGetTime()
    {
        SimpleDateFormat drFormat = new SimpleDateFormat("yyyyMMdd");
        Calendar drCalendar = Calendar.getInstance();
        return drFormat.format(drCalendar.getTime());
    }

    /**
     * @Auth Jiang Zhan
     * @Desc 获取每月的开始和结束时间
     * @Time 2020年09月24日15:59:43
     */
    public static Map<String,String> drGetMonthTime()
    {
        Map<String,String> drMap = new HashMap<>();
        LocalDate drCurrentDate = LocalDate.now();
        int drYear = drCurrentDate.getYear();
        int drMonth = drCurrentDate.getMonthValue();
        LocalDate drFirstDayOfMonth = LocalDate.of(drYear, drMonth, 1);
        LocalDateTime drStartOfDay = drFirstDayOfMonth.atStartOfDay();
        LocalDate drLastDayOfMonth = drFirstDayOfMonth.with(TemporalAdjusters.lastDayOfMonth());
        LocalDateTime drEndOfDay = drLastDayOfMonth.atTime(LocalTime.MAX);
        drMap.put("drEndOfDay",String.valueOf(drEndOfDay.atZone(ZoneId.systemDefault()).toEpochSecond()));
        drMap.put("drStartOfDay",String.valueOf(drStartOfDay.atZone(ZoneId.systemDefault()).toEpochSecond()));
        return drMap;
    }
}
